﻿using MediatR;
using S.Authorization.Common.Dto;
using S.Authorization.Common;
using S.Authorization.Read.API.Application.Command.UserCommand;
using S.Authorization.Infrastructure.Interface.User;
using S.Authorization.Domain.Model.User;

namespace S.Authorization.Read.API.Application.CommandHandlers.UserCommandHandler
{
    /// <summary>
    /// 人员管理显示
    /// </summary>
    /// <param name="userName">员工姓名</param>
    /// <param name="departmentId">所在部门</param>
    /// <param name="state">员工状态</param>
    /// <returns></returns>
        public class UserGetAllPageCommandHandler : IRequestHandler<UserGetAllPageCommand, Pager<GetUserListDto>>,IRequestHandler<GetUserCommand,UsersModel>
        {
            #region 注入
            private readonly IUserModellRepository repository;
            public UserGetAllPageCommandHandler(IUserModellRepository repository)
            {
                this.repository = repository;
            }
            #endregion
            public async Task<Pager<GetUserListDto>> Handle(UserGetAllPageCommand request, CancellationToken cancellationToken)
            {
                List<GetUserListDto> list = await repository.GetUserList(request.UserName, request.DepartmentId, request.State);
                int totalCount=list.Count;
                int pageCount = (int)Math.Ceiling(totalCount * 1.0 / request.PageSize);
                list=list.Skip((request.PageIndex-1)*request.PageSize).Take(request.PageSize).ToList();
                Pager<GetUserListDto> pager = new Pager<GetUserListDto>()
                {
                    resultData = list,
                    PageCount = pageCount,
                    TotalCount = totalCount
                };
                return pager;
            }
            /// <summary>
            /// 根据用户ID返填用户信息
            /// </summary>
            /// <param name="request"></param>
            /// <param name="cancellationToken"></param>
            /// <returns></returns>
            /// <exception cref="NotImplementedException"></exception>
            public async Task<UsersModel> Handle(GetUserCommand request, CancellationToken cancellationToken)
            {
                var list =await repository.GetAllAsync();
                var user = list.FirstOrDefault(x => x.UserId == request.ID);
                if (user != null)
                {
                    return user;
                }
                else
                {
                    return new UsersModel();
                }
            }
        }
}
